package com.wit.dao.impl;

import hibernate.HibernateSessionFactory;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.wit.dao.WorklogDao;
import com.wit.po.Adgenda;
import com.wit.po.Worklog;

public class WorklogDaoImpl implements WorklogDao {

	
	public boolean addWorklog(Worklog worklog) {
		
		Session session = null;
		boolean flag = false;
		try {
			session = HibernateSessionFactory.getSession();
			Transaction tx = session.beginTransaction();
			session.save(worklog);
			tx.commit();
			flag = true;
		
		} catch (Exception e) {

			flag = false;
		} finally {

			if(session != null && session.isOpen())
				session.close();
		}
		return flag;
	}

	
	public Worklog getWorklogById(Integer logId) {
		
		if(logId == null)
			return null;
		Session session = null;
		Worklog worklog = null;
		try {
			session = HibernateSessionFactory.getSession();
			
			String hql = "from Worklog worklog where worklog.logId=?";
			Query query = session.createQuery(hql);
			query.setInteger(0, logId);
			
			worklog = (Worklog)query.uniqueResult();
		
		} catch (Exception e) {

			e.printStackTrace();
		} finally {

			if(session != null && session.isOpen())
				session.close();
		}
		return worklog;
	}

	
	public List<Worklog> getWorklogList(String employeeId, String date) {
		
		if(employeeId == null || date == null)
			return null;
		Session session = null;
		List<Worklog> worklogList = null;
		try {
			session = HibernateSessionFactory.getSession();
			
			String hql = "from Worklog worklog where worklog.employee.employeeId=? and DATE(worklog.logdate)=?";
			Query query = session.createQuery(hql);
			
			query.setString(0, employeeId);
			query.setString(1, date);
			
			worklogList = (List<Worklog>)query.list();
		
		} catch (Exception e) {

			e.printStackTrace();
		} finally {

			if(session != null && session.isOpen())
				session.close();
		}
		return worklogList;
	}

	
	public boolean removeWorklog(Worklog worklog) {
		
		Session session = null;
		boolean flag = false;
		try {
			session = HibernateSessionFactory.getSession();
			Transaction tx = session.beginTransaction();
			
			session.delete(worklog);
			
			tx.commit();
			flag = true;
		
		} catch (Exception e) {

			flag = false;
		} finally {

			if(session != null && session.isOpen())
				session.close();
		}
		return flag;
	}

	
	public boolean updateWorklog(Worklog worklog) {
		
		Session session = null;
		boolean flag = false;
		try {
			session = HibernateSessionFactory.getSession();
			Transaction tx = session.beginTransaction();
			
			session.update(worklog);
			
			tx.commit();
			flag = true;
		
		} catch (Exception e) {

			flag = false;
		} finally {

			if(session != null && session.isOpen())
				session.close();
		}
		return flag;
	}

}
